package com.xxxx.rpc.rabbitmq;

import com.github.qcloudsms.httpclient.HTTPException;
import com.rabbitmq.client.Channel;
import com.xxxx.common.utils.SendSms;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * RabbitMQ监听消息并处理
 */
@Component
public class SmsConsumer {

    //监听，当收到消息的时候，就交给 @RabbitHandler 的方法处理
    @RabbitListener(
            bindings = {
                    @QueueBinding(value = @Queue(
                            value = "sms_queue", durable = "false", autoDelete = "false"
                    ), exchange = @Exchange(
                            value = "sms_exchange", durable = "false", autoDelete = "false", type = "topic"
                    ),
                            key = "test.sms"
                    )
            }
    )
    @RabbitHandler
    public void realSendMail(@Payload String phoneNumber, Channel channel, @Headers Map headers) throws HTTPException, IOException {
        SendSms sendSms = new SendSms();
        //发送短信
        int result = sendSms.sendSms(phoneNumber);
        if (result == 0) {
            System.out.println("手机号:" + phoneNumber + "发送短信成功");
        }
        try {
            channel.basicAck((Long) headers.get(AmqpHeaders.DELIVERY_TAG), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}